package com.tools.controller;

import com.tools.common.beans.constant.ControllerConstant;
import com.tools.common.beans.vo.Result;
import com.tools.common.exception.ToolException;
import com.tools.generator.config.ToolDataSource;
import com.tools.generator.entity.DataSourceEntity;
import com.tools.generator.entity.TableEntity;
import com.tools.generator.service.DataSourceService;
import com.tools.generator.utils.DbUtils;
import com.tools.generator.utils.QueryUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源管理
 *
 * @author Admin
 */
@Slf4j
@RestController
@RequestMapping(ControllerConstant.API_DATASOURCE)
public class DataSourceController extends BaseController {

    @Autowired
    private DataSourceService datasourceService;

    /**
     * 基础路径
     */
    private final String prefix = "generate/";


    @GetMapping(value = {"/{page}.html"})
    public ModelAndView allPage(@PathVariable("page") String page) {
        return jumpPage(prefix + page);
    }

    @GetMapping("source-edit")
    public ModelAndView editPage(@RequestParam Long id) {
        DataSourceEntity byId = datasourceService.getById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("dataSource", byId);
        modelAndView.setViewName(prefix + "source-edit");
        return modelAndView;
    }

    @PostMapping("page")
    public Result page(DataSourceEntity query) {
        startPage(query.getPage(), query.getLimit());
        List<DataSourceEntity> page = datasourceService.page(query);
        return getDataTable(page);
    }

    @GetMapping("list")
    public Result<List<DataSourceEntity>> list() {
        List<DataSourceEntity> list = datasourceService.getList();
        return Result.OK(list);
    }

    @GetMapping("{id}")
    public Result<DataSourceEntity> get(@PathVariable("id") Long id) {
        DataSourceEntity data = datasourceService.getById(id);
        return Result.OK(data);
    }

    /**
     * 测试连接数据源
     *
     * @param id 数据源ID
     * @return 连接结果
     */
    @GetMapping("test/{id}")
    public Result<String> test(@PathVariable("id") Long id) {
        try {
            DataSourceEntity entity = datasourceService.getById(id);
            DbUtils.getConnection(new ToolDataSource(entity));
            return Result.Tip("连接成功", 0);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ToolException("连接失败");
        }
    }

    /**
     * 新增数据源
     *
     * @param entity 数据源实体
     * @return
     */
    @PostMapping("save")
    public Result<String> save(@RequestBody DataSourceEntity entity) {
        datasourceService.save(entity);
        return Result.OK();
    }

    /**
     * 更新
     * @param entity
     * @return
     */
    @PutMapping("update")
    public Result<String> update(@RequestBody DataSourceEntity entity) {
        datasourceService.updateById(entity);
        return Result.OK();
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping("delete")
    public Result<String> delete(@RequestBody Long[] ids) {
        datasourceService.removeBatchByIds(Arrays.asList(ids));
        return Result.OK();
    }

    /**
     * 根据数据源ID，获取全部数据表
     *
     * @param id 数据源ID
     */
    @GetMapping("table/list/{id}")
    public Result<List<TableEntity>> tableList(@PathVariable("id") Long id) {
        try {
            // 获取数据源
            ToolDataSource datasource = datasourceService.get(id);
            // 根据数据源，获取全部数据表
            List<TableEntity> tableList = QueryUtils.getTableList(datasource);
            return Result.OK(tableList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ToolException("数据源配置错误，请检查数据源配置");
        }
    }


}